function openCatalogue(e) {
    return "[+]" === e.innerHTML ? $(e).attr("title", "收起").html("[-]").parent().next().show() : $(e).attr("title", "展开").html("[+]").parent().next().hide(), e.blur(), !1
}

/**
 *拼接评论内容
 */
function splitJointCommentHtml(result){
    let ht = '';
    for (let i = 0; i < result.data.list.length; i++) {
        let showReplyHtml = '';
        if(result.data.list[i].replyCount>0){
            showReplyHtml = '<a class="" href="javascript:" role="button" articleId="'+result.data.list[i].articleId+'" commentId="'+result.data.list[i].id+'" replyToMemberId="'+result.data.list[i].memberId+'" onclick="return showReply(this);">查看'+result.data.list[i].replyCount+'条回复</a>'
        }

        let upHtml = '';
        if(result.data.list[i].likeStatus===1){
            upHtml='icon-thumbs-up';
        }else {
            upHtml= 'icon-thumbs-up-alt';
        }

        let downHtml = '';
        if(result.data.list[i].dislikeStatus===1){
            downHtml='icon-thumbs-down';
        }else {
            downHtml= 'icon-thumbs-down-alt';
        }

        ht=ht+'<div class="comment media">'
            +'      <div class="media-left">'
            +'          <a class="avatar avatar-lg" href="javascript:">'
            +'              <img src="'+result.data.list[i].headPhoto+'" alt="...">'
            +'          </a>'
            +'      </div>'
            +'      <div class="comment-body media-body">'
            +'          <a class="comment-author" href="javascript:">'+result.data.list[i].nickname+'</a>'
            +'          <div class="comment-meta">'
            +'              <span class="date">'+new Date(result.data.list[i].createTime).format("yyyy-MM-dd hh:mm:ss")+'</span>'
            +'          </div>'
            +'          <div class="comment-content">'
            +'              <p>'+result.data.list[i].content+'</p>'
            +'          </div>'
            +'          <div class="comment-actions">'
            +'              <a class="text-like icon wb-heart thumbs-up '+upHtml+' like-btn"  commentId="'+result.data.list[i].id+'" likeType="1"  status="'+result.data.list[i].likeStatus+'" onclick="return commentLike(this);" role="button">'+(result.data.list[i].likeCount===0?"":result.data.list[i].likeCount)+'</a>'
            +'              <a class="text-like icon wb-heart thumbs-up '+downHtml+'  dislike-btn"  commentId="'+result.data.list[i].id+'" likeType="2"  status="'+result.data.list[i].dislikeStatus+'" onclick="return commentLike(this);" role="button">'+(result.data.list[i].dislikeCount===0?"":result.data.list[i].dislikeCount)+'</a>'
            +'              <a class="active" href="javascript:" role="button" articleId="'+result.data.list[i].articleId+'" commentId="'+result.data.list[i].id+'" replyToMemberId="'+result.data.list[i].memberId+'" openStatus="0" replyTargetType="1" onclick="return openReply(this);"> 回复</a>'
            +'          </div>'
            +showReplyHtml
            +'      </div>'
            +'</div>';
    }
    return ht;
}

/**
 * 显示评论
 */
function showComment(e){
    const articleId = $(e).attr('articleId');
    const pageCurrent = $(e).attr('pageCurrent');

    $.get('/comment', {
        articleId:articleId,
        pageCurrent:pageCurrent,
        pageSize:10
    }, function(result) {
        if (result) {
            const pageCurrent = result.data.pageCurrent;
            const totalPage = result.data.totalPage;
            if(totalPage<=pageCurrent){
                $(e).hide();
            }else{
                $(e).attr('pageCurrent',pageCurrent+1);
            }
            $(e).before(splitJointCommentHtml(result));
        }
    }, 'json');
}

/**
 * 初始化评论
 * @type {jQuery|HTMLElement}
 */
function initComments(){
    const $comments = $(".margin-horizontal-20");
    const pageCurrent = 1;
    $.get('/comment', {
        articleId:articleId,
        pageCurrent:pageCurrent,
        pageSize:10
    }, function(result) {
        if (result) {
            if(result.data.list.length<1){
                $comments.append('<button type="button" class="btn btn-sm col-xs-12" articleId="'+articleId+'" pageCurrent="'+pageCurrent+'" >暂无评论哦，快来评论一下吧！</button>');
            }else {
                const pageCurrent = result.data.pageCurrent;
                const totalPage = result.data.totalPage;
                $comments.append(splitJointCommentHtml(result));
                if(totalPage>pageCurrent){
                    $comments.append('<button type="button" class="btn btn-sm col-xs-12" articleId="'+articleId+'" pageCurrent="'+pageCurrent+1+'" onclick="return showComment(this);">点击查看更多评论</button>');
                }
            }
        }
    }, 'json');
}

if(whetherAllowScore==='1'){
    initComments();
}

/**
 *拼接回复内容
 */
function splitJointReplyHtml(result){
    let ht = '<div class="comments">';
    for (let i = 0; i < result.data.list.length; i++) {
        let htm = '';
        if(result.data.list[i].replyTargetType===2){
            htm='<a class="btn-link">@'+result.data.list[i].replyToMember.nickname+'</a>';
        }
        ht=ht+'                                                          <div class="comment media">\n' +
            '                                                                <div class="media-left">\n' +
            '                                                                    <a class="avatar avatar-lg" href="javascript:">\n' +
            '                                                                        <img src="'+result.data.list[i].replyFromMember.headPhoto+'" alt="...">\n' +
            '                                                                    </a>\n' +
            '                                                                </div>\n' +
            '                                                                <div class="comment-body media-body">\n' +
            '                                                                    <a class="comment-author" href="javascript:">'+result.data.list[i].replyFromMember.nickname+'</a>\n' +
            '                                                                    <div class="comment-meta">\n' +
            '                                                                        <span class="date">'+new Date(result.data.list[i].createTime).format("yyyy-MM-dd hh:mm:ss")+'</span>\n' +
            '                                                                    </div>\n' +
            '                                                                    <div class="comment-content">\n' +
            '                                                                        <p>'+htm+result.data.list[i].content+'</p>\n' +
            '                                                                    </div>\n' +
            '                                                                    <div class="comment-actions">\n' +
            '                                                                        <a class="text-like icon wb-heart thumbs-up '+(result.data.list[i].likeStatus===1?'icon-thumbs-up':'icon-thumbs-up-alt')+' like-btn" onclick="return replyLike(this);" role="button" replyId="'+result.data.list[i].id+'" likeType="1"  status="'+result.data.list[i].likeStatus+'">'+(result.data.list[i].likeCount === 0?"":result.data.list[i].likeCount)+'</a>\n' +
            '                                                                        <a class="text-like icon wb-heart thumbs-up '+(result.data.list[i].dislikeStatus===1?'icon-thumbs-down':'icon-thumbs-down-alt')+' dislike-btn" onclick="return replyLike(this);" role="button" replyId="'+result.data.list[i].id+'" likeType="2"  status="'+result.data.list[i].dislikeStatus+'">'+(result.data.list[i].dislikeCount === 0?"":result.data.list[i].dislikeCount)+'</a>\n' +
            '                                                                        <a href="javascript:" role="button" articleId="'+articleId+'" commentId="'+result.data.list[i].commentId+'" replyToMemberId="'+result.data.list[i].replyFromMemberId+'" openStatus="0" replyTargetType="2" onclick="return openReply(this);">回复</a>\n' +
            '                                                                    </div>\n' +
            '                                                                </div>\n' +
            '                                                            </div>\n';
    }
    ht = ht+'                                                        </div>';

    return ht;
}

/**
 * 显示回复
 */
function showReply(e){
    const articleId = $(e).attr('articleId');
    const commentId = $(e).attr('commentId');
    const replyToMemberId = $(e).attr('replyToMemberId');

    const pageCurrent = $(e).attr('pageCurrent');

    $.get('/reply', {
        replyToMemberId : replyToMemberId,
        articleId:articleId,
        commentId:commentId,
        pageCurrent:pageCurrent,
        pageSize:10
    }, function(result) {
        if (result) {
            const pageCurrent = result.data.pageCurrent;
            const totalPage = result.data.totalPage;
            if(totalPage<=pageCurrent){
                $(e).hide();
            }else{
                $(e).text("点击查看更多回复");
                $(e).attr('pageCurrent',pageCurrent+1);
            }
            $(e).before(splitJointReplyHtml(result));
        }
    }, 'json');
}

/**
 * 打开一级回复框
 * @param e
 */
function openReply(e) {
    const articleId = $(e).attr('articleId');
    const commentId = $(e).attr('commentId');
    const replyToMemberId = $(e).attr('replyToMemberId');
    const replyTargetType = $(e).attr('replyTargetType');
    let replyTargetId = commentId;
    if(replyTargetType==='2'){
        replyTargetId=replyToMemberId;
    }
    $(e).attr('openStatus') === '0' ? $(e).attr("openStatus", "1").after(
        "<form class=\"comment-reply\"  onsubmit=\"return false;\"  id=\"comment-reply-add-from\"  action=\"/reply\" method=\"post\">" +
        "<div class=\"form-group\">"+
        "<input type=\"hidden\" class=\"form-control\" name=\"articleId\" value=\""+articleId+"\" >"+
        "</div>"+
        "<div class=\"form-group\">"+
        "<input type=\"hidden\" class=\"form-control\" name=\"commentId\" value=\""+commentId+"\" >"+
        "</div>"+
        "<div class=\"form-group\">"+
        "<input type=\"hidden\" class=\"form-control\" name=\"replyToMemberId\" value=\""+replyToMemberId+"\" >"+
        "</div>"+
        "<div class=\"form-group\">"+
        "<input type=\"hidden\" class=\"form-control\" name=\"replyTargetId\" value=\""+replyTargetId+"\" >"+
        "</div>"+
        "<div class=\"form-group\">"+
        "<input type=\"hidden\" class=\"form-control\" name=\"replyTargetType\" value=\""+replyTargetType+"\" >"+
        "</div>"+
        "<div class=\"form-group\">\n" +
        "    <textarea class=\"form-control\" rows=\"5\" name='content' placeholder=\"回复内容…\"></textarea>\n" +
        "</div>\n" +
        '<div class="error-message text-center" >'+
        '   <span class="error-icon"></span>'+
        '   <span class="error-msg text-danger" ></span>'+
        '</div>'+
        "<div class=\"form-group\">\n" +
        "<button type=\"submit\" class=\"btn btn-primary\">发表回复</button>\n" +
        "<button type=\"button\" class=\"btn btn-link blue-grey-500\">取消</button>\n" +
        "</div>\n" +
        '</div>'+
        "</form>") : $(e).attr("openStatus", "0").next().remove();

    const $commentReplyAddForm = $("#comment-reply-add-from");
    $commentReplyAddForm.validate({
        rules: {
            articleId: {
                required: true,
            },
            commentId: {
                required: true,
            },
            replyToMemberId: {
                required: true,
            },
            content: {
                required: true,
            }
        },
        messages: {
            articleId:{
                required:"文章ID不能为空！"
            },
            commentId:{
                required:"评论ID不能为空！"
            },
            replyToMemberId:{
                required:"回复的用户ID不能为空！"
            },
            content: {
                required: "评论内容不能为空！"
            }
        },
        submitHandler:ajaxSubmit,
        errorLabelContainer:".error-msg",
        wrapper:"li",
        showErrors:function(errorMap,errorList) {
            if(errorList.length>0){
                $commentReplyAddForm.find(".error-msg").html(errorList[0].message);
            }else{
                $commentReplyAddForm.find(".error-msg").html("");
            }
        },
        onkeyup: false
    });
}

function ajaxSubmit(form) {

    const $form = $(form);

    if ($form.length === 1 && $form.validate()) {
        $.post(form.action, $form.serialize(),
            function(result) {
                if (result.status === 200) {
                    location.replace(result.data);
                } else if(result.status === 5001){
                    location.replace("/login.html?redirectURL="+location.pathname);
                }else {
                    $form.find(".error-msg").html(result.message);
                    $form.find(".error-msg").show();
                }
            }, 'json');
    }
}

/**
 * 文章点赞功能
 * @param e
 */
function like(e){

    const articleId =$(e).attr('articleId');
    const likeType=$(e).attr('likeType');
    const status=$(e).attr('status');

    if (status === '0') {
        $(e).attr('status', 1);
        $(e).removeClass("btn-warning");
        $(e).find('.num').text(parseInt($(e).find('.num').text()) + 1);

        if (likeType === '1') {
            const $dislikeBtn = $(e).parent().find('.dislike-btn');
            if($dislikeBtn.attr('status')==='1') {

                $dislikeBtn.find('.num').text(parseInt($dislikeBtn.find('.num').text()) - 1);
                $dislikeBtn.addClass("btn-warning");
                $dislikeBtn.attr('status', 0);
            }

        } else {
            const $likeBtn = $(e).parent().find('.like-btn');
            if($likeBtn.attr('status')==='1') {

                $likeBtn.find('.num').text(parseInt($likeBtn.find('.num').text()) - 1);
                $likeBtn.addClass("btn-warning");
                $likeBtn.attr('status', 0);
            }
        }

    } else {
        $(e).attr('status', 0);
        $(e).addClass("btn-warning");
        $(e).find('.num').text(parseInt($(e).find('.num').text()) - 1);
    }
    $.post("/article/like", {
            articleId:articleId,
            likeType:likeType,
            status:status==='0'?1:0
        },
        function(result) {
            if (result.status === 200) {
            } else if(result.status === 5001){
                location.replace("/login.html?redirectURL="+location.pathname);
            }else {
                alert(result.message);
            }
        }, 'json');
}


/**
 * 评论点赞功能
 * @param e
 */
function commentLike(e){

    const commentId =$(e).attr('commentId');
    const likeType=$(e).attr('likeType');
    const status=$(e).attr('status');
    if(status==='0' || status ==='' || status ==='null'){

        if(likeType==='1'){

            $(e).attr('status',1);
            $(e).addClass("icon-thumbs-up").removeClass("icon-thumbs-up-alt");
            $(e).text(parseInt($(e).text()===''?0:$(e).text())+1);

            const $dislikeBtn = $(e).parent().find('.dislike-btn');
            if($dislikeBtn.attr('status')==='1'){
                $dislikeBtn.text($dislikeBtn.text()===''?0:(parseInt($dislikeBtn.text()===''?0:$dislikeBtn.text())-1));
                $dislikeBtn.addClass("icon-thumbs-down-alt").removeClass("icon-thumbs-down");
                $dislikeBtn.attr('status',0);
            }

        }else {

            $(e).attr('status',1);
            $(e).addClass("icon-thumbs-down").removeClass("icon-thumbs-down-alt");
            $(e).text(parseInt($(e).text()===''?0:$(e).text())+1);

            const $likeBtn = $(e).parent().find('.like-btn');
            if($likeBtn.attr('status')==='1') {
                $likeBtn.text($likeBtn.text() === '' ? 0 : (parseInt($likeBtn.text() === '' ? 0 : $likeBtn.text()) - 1));
                $likeBtn.addClass("icon-thumbs-up-alt").removeClass("icon-thumbs-up");
                $likeBtn.attr('status', 0);
            }
        }

    }else{
        if(likeType==='1') {
            $(e).attr('status', 0);
            $(e).addClass("icon-thumbs-up-alt").removeClass("icon-thumbs-up");
            $(e).text($(e).text()===''?0:(parseInt($(e).text() === '' ? 0 : $(e).text()) - 1));
        }else {
            $(e).attr('status', 0);
            $(e).addClass("icon-thumbs-down-alt").removeClass("icon-thumbs-down");
            $(e).text($(e).text()===''?0:(parseInt($(e).text() === '' ? 0 : $(e).text()) - 1));
        }
    }
    $.post("/comment/like", {
            commentId:commentId,
            likeType:likeType,
            status:status==='0'||status==='' ||status==='null'?1:0
        },
        function(result) {
            if (result.status === 200) {
                //location.reload();
            } else if(result.status === 5001){
                location.replace("/login.html?redirectURL="+location.pathname);
            }else {
                alert(result.message);
            }
        }, 'json');
}


/**
 * 回复点赞功能
 * @param e
 */
function replyLike(e){

    const replyId =$(e).attr('replyId');
    const likeType=$(e).attr('likeType');
    const status=$(e).attr('status');
    if(status==='0' || status ==='' || status ==='null'){

        if(likeType==='1'){

            $(e).attr('status',1);
            $(e).addClass("icon-thumbs-up").removeClass("icon-thumbs-up-alt");
            $(e).text(parseInt($(e).text()===''?0:$(e).text())+1);


            const $dislikeBtn = $(e).parent().find('.dislike-btn');
            if($dislikeBtn.attr('status')==='1') {

                $dislikeBtn.text($dislikeBtn.text() === '' ? 0 : (parseInt($dislikeBtn.text() === '' ? 0 : $dislikeBtn.text()) - 1));
                $dislikeBtn.addClass("icon-thumbs-down-alt").removeClass("icon-thumbs-down");
                $dislikeBtn.attr('status', 0);
            }

        }else {
            const $likeBtn = $(e).parent().find('.like-btn');
            if($likeBtn.attr('status')==='1') {
                $likeBtn.text($likeBtn.text() === '' ? 0 : (parseInt($likeBtn.text() === '' ? 0 : $likeBtn.text()) - 1));
                $likeBtn.addClass("icon-thumbs-up").removeClass("icon-thumbs-up-alt");
                $likeBtn.attr('status', 0);
            }

            $(e).attr('status',1);
            $(e).addClass("icon-thumbs-down").removeClass("icon-thumbs-down-alt");
            $(e).text(parseInt($(e).text()===''?0:$(e).text())+1);
        }

    }else{
        if(likeType==='1') {
            $(e).attr('status', 0);
            $(e).addClass("icon-thumbs-up-alt").removeClass("icon-thumbs-up");
            $(e).text($(e).text()===''?0:(parseInt($(e).text() === '' ? 0 : $(e).text()) - 1));
        }else {
            $(e).attr('status', 0);
            $(e).addClass("icon-thumbs-down-alt").removeClass("icon-thumbs-down");
            $(e).text($(e).text()===''?0:(parseInt($(e).text() === '' ? 0 : $(e).text()) - 1));
        }
    }
    $.post("/reply/like", {
            replyId:replyId,
            likeType:likeType,
            status:status==='0'||status==='' ||status==='null'?1:0
        },
        function(result) {
            if (result.status === 200) {
                //location.reload();
            } else if(result.status === 5001){
                location.replace("/login.html?redirectURL="+location.pathname);
            }else {
                alert(result.message);
            }
        }, 'json');
}

$(function() {
    const $commentsAddForm = $("#comments-add-from");
    $commentsAddForm.validate({
        rules: {
            articleId: {
                required: true,
            },
            content: {
                required: true,
            }
        },
        messages: {
            articleId:{
                required:"文章ID不能为空！"
            },
            content: {
                required: "评论内容不能为空！"
            }
        },
        submitHandler:ajaxSubmit,
        errorLabelContainer:".error-msg",
        wrapper:"li",
        showErrors:function(errorMap,errorList) {
            if(errorList.length>0){
                $commentsAddForm.find(".error-msg").html(errorList[0].message);
            }else{
                $commentsAddForm.find(".error-msg").html("");
            }
        },
        onkeyup: false
    });


    /*
    *渲染点赞状态
    **/
    $.get("/article/like", {
            articleId:articleId
        },
        function(result) {
            if (result.status === 200) {
                for (var i = 0; i < result.data.length; i++) {
                    if(result.data[i].likeType===1){
                        $("#article-like-btn").attr('status',result.data[i].status);
                        if(result.data[i].status===1){
                            $("#article-like-btn").removeClass("btn-warning");
                        }
                    }
                    if(result.data[i].likeType===2){
                        $("#article-dislike-btn").attr('status',result.data[i].status);
                        if(result.data[i].status===1){
                            $("#article-dislike-btn").removeClass("btn-warning");
                        }
                    }
                }
            }
        }, 'json');


    /*
    *递增阅读数
    **/
    $.ajax({
        url: "/article/push-view-count?articleId="+articleId,
        type: "PUT",//POST、PUT、DELETE
        dataType: 'json',
        async: true,
        data: {
            articleId: articleId
        },
        success: function (result) {

        }
    });

});